package com.zlsy.thread.deadlock;


import java.util.concurrent.TimeUnit;

/**
 * @author zhouliang
 * @date 2020/5/12 20:43
 * <p>
 * 必定发生死锁的情况
 */
public class MustDeadLock implements Runnable {

    int flag = 1;

    private final static Object o1 = new Object();
    private final static Object o2 = new Object();

    public static void main(String[] args) {
        MustDeadLock r1 = new MustDeadLock();
        MustDeadLock r2 = new MustDeadLock();
        r1.flag = 1;
        r2.flag = 2;

        Thread t1 = new Thread(r1);
        Thread t2 = new Thread(r2);

        t1.start();
        t2.start();
    }


    @Override
    public void run() {
        System.out.println("flag = " + flag);
        if (flag == 1) {
            synchronized (o1) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (o2) {
                    System.out.println("r1 拿到了第二把锁！");
                }
            }
        }
        if (flag == 2) {
            synchronized (o2) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (o1) {
                    System.out.println("r2 拿到了第一把锁！");
                }
            }
        }
    }
}
